/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Services;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entity.MedicalRecord;
import Entity.Owner;
import Entity.Pet;
import Entity.PetPK;
import Services.exceptions.NonexistentEntityException;
import Services.exceptions.PreexistingEntityException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author itachiu
 */
public class PetJpaController implements Serializable {

    public PetJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Pet pet) throws PreexistingEntityException, Exception {
        if (pet.getPetPK() == null) {
            pet.setPetPK(new PetPK());
        }
        pet.getPetPK().setMEDICALRECORDidMEDICALRECORD(pet.getMedicalRecord().getIdMEDICALRECORD());
        pet.getPetPK().setOwnerPersonPersonId(pet.getOwner().getPersonPersonId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            MedicalRecord medicalRecord = pet.getMedicalRecord();
            if (medicalRecord != null) {
                medicalRecord = em.getReference(medicalRecord.getClass(), medicalRecord.getIdMEDICALRECORD());
                pet.setMedicalRecord(medicalRecord);
            }
            Owner owner = pet.getOwner();
            if (owner != null) {
                owner = em.getReference(owner.getClass(), owner.getPersonPersonId());
                pet.setOwner(owner);
            }
            em.persist(pet);
            if (medicalRecord != null) {
                medicalRecord.getPetList().add(pet);
                medicalRecord = em.merge(medicalRecord);
            }
            if (owner != null) {
                owner.getPetList().add(pet);
                owner = em.merge(owner);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findPet(pet.getPetPK()) != null) {
                throw new PreexistingEntityException("Pet " + pet + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Pet pet) throws NonexistentEntityException, Exception {
        pet.getPetPK().setMEDICALRECORDidMEDICALRECORD(pet.getMedicalRecord().getIdMEDICALRECORD());
        pet.getPetPK().setOwnerPersonPersonId(pet.getOwner().getPersonPersonId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Pet persistentPet = em.find(Pet.class, pet.getPetPK());
            MedicalRecord medicalRecordOld = persistentPet.getMedicalRecord();
            MedicalRecord medicalRecordNew = pet.getMedicalRecord();
            Owner ownerOld = persistentPet.getOwner();
            Owner ownerNew = pet.getOwner();
            if (medicalRecordNew != null) {
                medicalRecordNew = em.getReference(medicalRecordNew.getClass(), medicalRecordNew.getIdMEDICALRECORD());
                pet.setMedicalRecord(medicalRecordNew);
            }
            if (ownerNew != null) {
                ownerNew = em.getReference(ownerNew.getClass(), ownerNew.getPersonPersonId());
                pet.setOwner(ownerNew);
            }
            pet = em.merge(pet);
            if (medicalRecordOld != null && !medicalRecordOld.equals(medicalRecordNew)) {
                medicalRecordOld.getPetList().remove(pet);
                medicalRecordOld = em.merge(medicalRecordOld);
            }
            if (medicalRecordNew != null && !medicalRecordNew.equals(medicalRecordOld)) {
                medicalRecordNew.getPetList().add(pet);
                medicalRecordNew = em.merge(medicalRecordNew);
            }
            if (ownerOld != null && !ownerOld.equals(ownerNew)) {
                ownerOld.getPetList().remove(pet);
                ownerOld = em.merge(ownerOld);
            }
            if (ownerNew != null && !ownerNew.equals(ownerOld)) {
                ownerNew.getPetList().add(pet);
                ownerNew = em.merge(ownerNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                PetPK id = pet.getPetPK();
                if (findPet(id) == null) {
                    throw new NonexistentEntityException("The pet with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(PetPK id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Pet pet;
            try {
                pet = em.getReference(Pet.class, id);
                pet.getPetPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The pet with id " + id + " no longer exists.", enfe);
            }
            MedicalRecord medicalRecord = pet.getMedicalRecord();
            if (medicalRecord != null) {
                medicalRecord.getPetList().remove(pet);
                medicalRecord = em.merge(medicalRecord);
            }
            Owner owner = pet.getOwner();
            if (owner != null) {
                owner.getPetList().remove(pet);
                owner = em.merge(owner);
            }
            em.remove(pet);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Pet> findPetEntities() {
        return findPetEntities(true, -1, -1);
    }

    public List<Pet> findPetEntities(int maxResults, int firstResult) {
        return findPetEntities(false, maxResults, firstResult);
    }

    private List<Pet> findPetEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Pet.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Pet findPet(PetPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Pet.class, id);
        } finally {
            em.close();
        }
    }

    public int getPetCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Pet> rt = cq.from(Pet.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
